package com.ndood.payment.core.security.handler;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.ndood.core.properties.SecurityProperties;
import com.ndood.payment.pojo.v1.comm.vo.PaymentResultVo;

import lombok.extern.slf4j.Slf4j;

@Component("authenticationSuccessHandler")
@Slf4j
public class PaymentAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{
	
	@Autowired
	private ObjectMapper objectMapper;
	
	@Autowired
	private ClientDetailsService clientDetailsService;
	
	@Autowired
	private SecurityProperties securityProperties;
	
	@Autowired
	private AuthorizationServerTokenServices authorizationServerTokenServices;
	
	@SuppressWarnings("unchecked")
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		
		String clientId = securityProperties.getOauth2().getClients()[0].getClientId();
		ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
		if(clientDetails == null){
			throw new UnapprovedClientAuthenticationException("clientId对应的配置信息不存在:" + clientId);
		}
		TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, clientDetails.getScope(), "miniprogram");
		OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
		OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
		OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);

		PaymentResultVo result = PaymentResultVo.ok();
		Map<String,Object> map = Maps.newHashMap();
		map.put("access_token", token.getValue());
		map.put("token_type", token.getTokenType());
		map.put("refresh_token", token.getRefreshToken().getValue());
		map.put("expires_in", String.valueOf(token.getExpiresIn()));
		result.setData(map);
		String json = objectMapper.writeValueAsString(result);
		
		StringBuilder sb = new StringBuilder("\n");
		sb.append("AAAAAAAAAAAAAAA登录成功AAAAAAAAAAAAAAA").append("\n");
		sb.append(JSON.toJSON(getHeadersInfo(request))).append("\n");
		sb.append(JSON.toJSON(request.getParameterMap())).append("\n");
		sb.append("返回结果:").append(json).append("\n");
		sb.append("AAAAAAAAAAAAAAA登录成功AAAAAAAAAAAAAAA").append("\n\n");
		log.error(sb.toString());
		
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(json);
		response.getWriter().flush();
		
	}

	/**
	 * 获取请求头信息
	 */
	private Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
	
}
